/**
 * 初始化详情对话框
 */
var CmsAuthInfoInfoDlg = {
    cmsAuthInfoInfoData: {}
};

/**
 * 清除数据
 */
CmsAuthInfoInfoDlg.clearData = function () {
    this.cmsAuthInfoInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
CmsAuthInfoInfoDlg.set = function (key, val) {
    this.cmsAuthInfoInfoData[key] = (typeof val == "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
CmsAuthInfoInfoDlg.get = function (key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
CmsAuthInfoInfoDlg.close = function () {
    parent.layer.close(window.parent.CmsAuthInfo.layerIndex);
}

/**
 * 收集数据
 */
CmsAuthInfoInfoDlg.collectData = function () {
    this
        .set('id')
        .set('userId')
        .set('demandId')
        .set('handleStatus')
        .set('connectStatus')
        .set('houseStatus')
        .set('policyStatus')
        .set('legalPersonStatus')
        .set('weiliLoanStatus')
        .set('creditCardStatus')
        .set('recommendStatis')
        .set('loanStatus')
        .set('reserve1Status')
        .set('reserve2Status')
        .set('loanAmount')
        .set('remark')
        .set('createTime')
        .set('updateTime')
        .set('isActive');
}

/**
 * 提交添加
 */
CmsAuthInfoInfoDlg.addSubmit = function () {

    this.clearData();
    this.collectData();

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/cmsAuthInfo/add", function (data) {
        Feng.success("添加成功!");
        window.parent.CmsAuthInfo.table.refresh();
        CmsAuthInfoInfoDlg.close();
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.cmsAuthInfoInfoData);
    ajax.start();
}

/**
 * 提交修改
 */
CmsAuthInfoInfoDlg.editSubmit = function () {

    this.clearData();
    this.collectData();

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/cmsAuthInfo/update", function (data) {
        Feng.success("修改成功!");
        window.parent.CmsAuthInfo.table.refresh();
        CmsAuthInfoInfoDlg.close();
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.cmsAuthInfoInfoData);
    ajax.start();
}


$(function () {

});


/*******************************************
 *  新方法，新添加;
 *  sam 2018.10.24;
 * */


$(function () {
    // CmsAuthInfoInfoDlg

    var url = {
        host: location.origin, //主域名
        add: "/cmsAuthInfo/add",
        update: "/cmsAuthInfo/update",
        detail: "/cmsUserDemand/getUserList",
    };
    var domKeys = {ids: []};
    Object.defineProperty(domKeys, 'set', {
        /**
         * 获取dom 的id 兼容上面的代码;
         * */
        value: function (key) {
            this.ids.push(key);
            return this;
        }
    });
    CmsAuthInfoInfoDlg.post = new function (url) {
        CmsAuthInfoInfoDlg.collectData.call(domKeys);
        var $ajax = {
            ids: domKeys.ids
        };
        $ajax.getPostObj = function () { //获取数据;
            var obj = {
                pages: [], //传递页面数据对象
                sendData: {},  //发送对象;
                tags: {},
            };

            $ajax.ids.forEach(function (id) {
                var tag = $('#' + id);
                obj.tags[id] = tag;
                if (tag.length) {
                    obj.pages.push({"id": id, 'tagName': tag[0].tagName, 'value': tag.val(),});
                    obj.sendData[id] = tag.val();
                } else {
                    obj.pages.push({"id": id, 'tagName': '', value: ''});
                    obj.sendData[id] = "";
                }
            });
            return obj;
        };


        return {
            [url.add]: function (data, fun) {
                // $ajax.getPostObj()
            },
            [url.update]: function (id, fun) {
                $.post(url.host + '/cmsAuthInfo/getOne', {id: id}, function (data) {
                    if (typeof  fun === 'function') fun(data, false);
                });

                var button = $("#detailButton");
                button.show();
                button.find("button").click(function () {
                    var postData = {};
                    CmsAuthInfoInfoDlg.post.objHtml.forEach(function (dom) {
                        if (dom.attr('id')) {
                            postData[dom.attr('id')] = $(dom).val()
                        } else {
                            // console.log(dom, '没有id')
                        }
                    });
                    CmsAuthInfoInfoDlg.post.objErrorKey.forEach(function(obj){  //没有放进页面的id;
                        postData[obj.key] = obj.value;
                    });
                    if(postData["demandDetail"] == null || postData["demandDetail"] == ""){
                        alert("用户贷款需求不能为空");
                        return;
                    }
                    if(postData["loanAmount"] != null){
                        var reg = /^[0-9]*$/;
                        if (!reg.test(postData["loanAmount"])) {
                            alert("放款金额填写错误")
                            return ;
                        }
                    }
                    
                    $.ajax({
                        type:"POST",
                        url:url.host + url.update,
                        data:postData,
                        success:function (data) {
                            Feng.success("修改成功!");
                            window.parent.CmsAuthInfo.table.refresh();
                            CmsAuthInfoInfoDlg.close();
                        },
                        error:function (e) {
                            Feng.error("修改失败!" + e.responseJSON.message );
                        }
                    })
                })
            },
            [url.detail]: function (id, fun) {
                $.post(url.host + '/cmsAuthInfo/getOne', {id: id}, function (data) {
                    if (typeof  fun === 'function') fun(data, true);
                })

                //提交信息
                $.post(url.detail, {'id': id}, function (data) {
                    function copy(data, row) {
                        $(row).parent().parent().show();
                        data.forEach(function (d) {
                            var copyRow = row.clone();
                            var dd = $(copyRow).find("span");
                            $(dd[0]).text(d.createTime);
                            $(dd[1]).text(d.demandDetail);
                            row.parent().append(copyRow);
                        });
                        row.remove()
                    }
                    copy(data, $("#" + 'detailRow'));
                })
            }
        };
    }(url);

    CmsAuthInfoInfoDlg.post.getStorage = function (key, id, fun) {  //获取处理
        // console.log(arguments, 'arg', url[key])
        if (typeof CmsAuthInfoInfoDlg.post[url[key]] === "function") {
            CmsAuthInfoInfoDlg.post[url[key]](id, function (data, disabled) {
                fun(data, disabled)
            })
        } else {
            console.log("function not", key)
        }
    };

    CmsAuthInfoInfoDlg.post['writeValue'] = function (storage, disabled) { //写入内容
        var arr = [];
        var arrKey = [];
        CmsAuthInfoInfoDlg.post.servierKeys = ["handleStatus","legalPersonStatus", "creditCardStatus", "connectStatus", "houseStatus", "userPhone", "recommendStatis", "remark", "updateTime", "policyStatus", "cmsAuthInfoId", "demand", "loanAmount", "reservel1Status", "demandId", "demandDetail","demand_detail", "reserve2Status", "createTime", "loanStatus", "handleStatus", "id", "weiliLoanStatus"];
        CmsAuthInfoInfoDlg.post.servierKeys.forEach(function(str){
            if(! (str in storage)){   //合并没有的键，并为空
                storage[str] = null;
            }
        });
        for (var key in  storage) {
            arr.push(setValue(key));
        }

        function setValue(key) {
            var tag = $("#" + key);
            if (tag.length) {
                if (tag[0].tagName === "SELECT") {
                    tag.find("option[value='" + storage[key] + "']").attr("selected", true);
                } else {
                    tag.val(storage[key]);
                }
                tag.attr("disabled", disabled)
            } else {
                arrKey.push({'key':key,'value': storage[key]})
            }
            return tag;
        }

        CmsAuthInfoInfoDlg.post.objHtml = arr;
        CmsAuthInfoInfoDlg.post.objErrorKey = arrKey;
    };

    CmsAuthInfoInfoDlg.post['detail'] = function (storage) {
        CmsAuthInfoInfoDlg.post[url.detail]({id: storage.id}, function (data) {
            var createTime = data.createTime;
            var demandDetail = data.demandDetail;

        });
    };

    CmsAuthInfoInfoDlg.post.start = function () {
        var run = location.search.match(/run=([\d\w]*)/); //初始化执行
        var id = location.pathname.split("/")[location.pathname.split("/").length - 1];
        var key = run[1];

        // id = 10634; //测试

        CmsAuthInfoInfoDlg.post.getStorage(key, id, function (storage, disabled) {
            CmsAuthInfoInfoDlg.post['writeValue'](storage, disabled);  //执行写入;

        }); //获取详情;
    };


    CmsAuthInfoInfoDlg.post.start();

});



